/*
 * 24/10/2011 - 13:41
 */
package org.nettyflux.tcp;

import java.io.IOException;
import org.nettyflux.communicator.ProtocolFacade;
import org.nettyflux.mailbox.MailBox;
import org.nettyflux.mailbox.ReceiveListener;
import org.nettyflux.netmessages.NetworkMessage;

/**
 * @author Victor Williams Stafusa da Silva
 */
public class TCPProtocolFacade implements ProtocolFacade<TCPHost> {

    private static final TCPProtocolFacade SINGLETON = new TCPProtocolFacade();

    private final Object[] slots;

    private TCPProtocolFacade() {
        this.slots = new Object[65536];
    }

    public static TCPProtocolFacade getInstance() {
        return SINGLETON;
    }

    public synchronized void accept(MailBox<NetworkMessage> mailbox, int port) throws IOException {
        if (slots[port] != null) throw new IOException("Port already in use.");
        TCPServerCommunicator communicator = new TCPServerCommunicator(mailbox, port);
        slots[port] = communicator;
    }

    private TCPClientCommunicator communicator(TCPHost host) throws IOException {
        Object obj;
        synchronized (this) {
            obj = slots[host.getPort()];
        }
        if (obj == null) throw new IOException("Port not connected.");
        if (!(obj instanceof TCPClientCommunicator)) {
            throw new IOException("Port not connected to a client.");
        }
        TCPClientCommunicator comm = (TCPClientCommunicator) obj;
        if (!(comm.getClient().equals(host))) {
            throw new IOException("Port not connected to this client.");
        }
        return comm;
    }

    @Override
    public void send(TCPHost host, byte[] mesage) throws IOException {
        communicator(host).send(mesage);
    }

    @Override
    public void receiveBlocking(TCPHost host, byte[] mesage) throws InterruptedException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void addReceiveListener(TCPHost host, ReceiveListener<byte[]> listener) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void removeReceiveListener(TCPHost host, ReceiveListener<byte[]> listener) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void closeAll() throws IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
